package cn.com.callback

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import cn.com.elite.EliteBean;
import cn.com.elite.PropertiesUtil;
import cn.com.elite.Util;
import java.util.Map;
import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import net.sf.json.JSONArray;
import java.net.URLEncoder;
/**
 * 
 * @author msjykf
 * 短信调度任务 取模板设置发送区间内 短信未发送并且模板无需审核或已经审核的数据
 * 发送通道：梦网直销
 *
 */
public class SmsSendMwzxTask implements CallBackInvoke{
	private static final Log log=LogFactory.getLog(SmsSendMwzxTask.class);
	public void doCallBack(EliteBean eliteBean,String callBack,Map map,String body){
		try {
			def startdate=Util.getNowString("yyyy-MM-dd HH:mm:ss");
			PropertiesUtil pt= new PropertiesUtil();
			def k = 0;
			def timestamp = Util.getNowString("MMddHHmmss");
			def userid = pt.readValue("mwzx_userid");
			def pwd = Util.getMD5Str(userid+pt.readValue("sms_str")+pt.readValue("mwzx_pwd")+timestamp); //userid + 固定字符串+ pwd(明文) + 时间戳，再进行MD5加密
			def ipport = pt.readValue("sms_ip")+":"+pt.readValue("mwzx_port");
			def charset = "utf-8"; //设置字符集
			def timeout = 100000; //设置请求超时时间
			def enableSSLflag = 0;
			def url = "http://"+ipport+"/sms/v2/std/multi_send";
			Map headMap=new HashMap(); //设置头文件
			headMap.put("Content-Type","application/json");
			JSONObject josnbody = new JSONObject();
			josnbody.put("userid",userid);
			josnbody.put("pwd",pwd);
			josnbody.put("timestamp",timestamp);
			while(k<20) {
				def guid = Util.getGuid();
				//log.debug("guid:"+guid);
				def unums = eliteBean.update("update sms_send_task set temp_guid ='"+guid+"' where smsno in (select smsno from (select tk.smsno from sms_send_task tk left join sms_send_batch sb on tk.batch_id=sb.batch_id left join sms_template_search st on tk.sms_id=st.sms_id left join triggermode tg on st.relation_id=tg.doctemplate_id where tk.temp_guid is null and tk.state=0 and sb.state>=3 and sb.checkstate in(0,2) and sb.batchstate=0 and nvl(st.pipe,tk.pipe)=2 and to_char(sysdate,'hh24:mi')>=nvl(tg.definestarttime,'00:00') and to_char(sysdate,'hh24:mi')<=nvl(tg.defineendtime,'23:59') order by st.priority) where rownum<=100)","dataSource");
				log.debug("短信发送获取记录数："+unums);
				if(unums==0) {
					break;
				}else if(unums>0 && unums<100) {
					k = 100;
				}else if(unums==100) {
					k++;
				};
				def list = eliteBean.chaxun_sqlRowSet("select smsno,batch_id,sms_id,phone,msg,exno from sms_send_task where temp_guid ='"+guid+"'","dataSource");
				JSONObject multimt = new JSONObject();
				JSONArray arr = new JSONArray();
				while(list.next()){
					def smsno = list.getString(1);
					multimt.put("mobile",list.getString(4));
					multimt.put("content",URLEncoder.encode(list.getString(5),"gbk"));
					multimt.put("svrtype",list.getString(3));
					//multimt.put("exno",list.getString(6));
					multimt.put("exno","");//20190325扩展号传空
					multimt.put("custid",list.getString(2));
					multimt.put("exdata",smsno);
					arr.add(multimt);
				};
				josnbody.put("multimt",arr);
				//log("发送的报文"+JSONObject.fromObject(josnbody).toString());
				
				//20190718添加异常保护机制
				def ppresult=0;
				try {
					def msgjson = Util.doHttpPostUseHead(url,JSONObject.fromObject(josnbody).toString(),charset,timeout,enableSSLflag,headMap);
					JSONObject obj = JSONObject.fromObject(msgjson);
					log.debug("obj:"+obj);
					ppresult=obj.get("result");
				}catch(Exception e) {
					log.error("ErrorMessage:",e);
					ppresult=-1;
				}
				def state=0;
				if(ppresult==0) {
					String[] data=new String[3];
					data[0] = "insert into sms_send(smsno,batch_id,sms_id,customer_guid,sk_invpty,invpty_name,phone,msg,state,priority,pipe,createdate,createby,creategp,stime,exno) select smsno,batch_id,sms_id,customer_guid,sk_invpty,invpty_name,phone,msg,1,priority,pipe,sysdate,createby,creategp,sysdate,exno from sms_send_task where temp_guid ='"+guid+"'";
					data[1] = "update sms_send_batch sb set tosendsum=(select sb.tosendsum+t1.totalnum from(select batch_id,count(*) as totalnum from sms_send_task where temp_guid ='"+guid+"' group by batch_id) t1 where t1.batch_id=sb.batch_id) where exists (select 1 from (select batch_id,count(*) as totalnum from sms_send_task where temp_guid ='"+guid+"' group by batch_id) t1 where t1.batch_id=sb.batch_id)";
					data[2] = "delete from sms_send_task where temp_guid ='"+guid+"'";
					int[] sqlresult = eliteBean.updateBatch(data,"dataSource");
				}else {
					eliteBean.update("update sms_send_task set temp_guid=null,trialcount=trialcount+1 where temp_guid ='"+guid+"'","dataSource");
				};
			};
			def enddate=Util.getNowString("yyyy-MM-dd HH:mm:ss");
			log.debug("\n"+"K:"+k+"\n"+"startdate:"+startdate+"\n"+"enddate:"+enddate);
		}catch(Exception e) {
			log.error("ErrorMessage:",e);
		}
	}	
}